package cn.template.controllers;

import cn.template.models.Company;
import cn.template.models.common.PagingResponse;
import cn.template.models.exceptions.BadRequestException;
import cn.template.services.CompanyService;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;


/**
 * 对象属性         @ApiModelProperty     用在参数对象的字段上
 * 协议集描述       @Api                  用在Conntroller类上
 * 协议描述         @Operation         用在controller方法上
 * Response集      @ApiResponses         用在controller方法上
 * Response        @ApiResponse          用在@ApiResponses里面
 * 非对象参数集      @ApilmplicitParams    用在controller方法上
 */
@RestController
@RequestMapping("/api/company")
@Api(value = "企业接口")
public class CompanyController extends BaseController<CompanyService> {
    private static  final  Logger logger = LogManager.getLogger();

    @Autowired
    public void setService(CompanyService service) {
        this.service = service;
    }

    @GetMapping()
    @Operation(description = "分页获取企业列表")
    public PagingResponse<Company> getAll(@RequestParam(value = "name", defaultValue = "") String name,
                                          @RequestParam(value = "page", defaultValue = "1") int page,
                                          @RequestParam(value = "size", defaultValue = "10") int size) {
        Page<Company> paging = this.service.getByName(page, size, name);
        return new PagingResponse<>(paging);
    }

    @GetMapping("/{id}")
    @Operation(description = "根据id获取企业信息")
    public Company get(@PathVariable long id) {
        Company company = this.service.getById(id);
        return company;
    }

    @PutMapping("/{id}")
    @Operation(description = "根据id更新企业信息")
    public Company update(@PathVariable long id, @RequestBody Company post) {
        if (!post.isSameId(id)) {
            throw new BadRequestException(String.format("the target record didn't match, postId=%s, pathId=%s", post.getId(), id));
        }

        Company origin = this.service.getById(id);
        origin.update(post);
        return this.service.save(origin);
    }

    @PostMapping
    @Operation(description = "新增企业信息")
    public Company create(@RequestBody Company post) {
        return this.service.save(post);
    }

    @DeleteMapping("/{id}")
    @Operation(description = "根据id删除企业信息")
    public boolean delete(@PathVariable long id) {
        return this.service.delete(id);
    }
}
